from datetime import datetime
import time

from django import http
from django.shortcuts import render
from django.views.generic import View
from meiduo_mall.utils.my_category import get_categories
from goods.models import GoodsCategory, SKUSpecification, GoodCategoryVisit
from goods.models import SPU, SKU
from django.core.paginator import Paginator
from meiduo_mall.utils.login_required import MyLoginRequest
from django_redis import get_redis_connection
import json


class SKUListView(View):
    def get(self, request, category_id, page_id):

        # 获取排序根据
        sort = request.GET.get('sort', 'default')

        # 获取分类信息
        categories = get_categories()

        category = GoodsCategory.objects.get(id=category_id)
        # 获取商品列表
        if sort == 'price':
            sku_sort = '-price'
        elif sort == 'hot':
            sku_sort = '-sales'
        else:
            sku_sort = '-create_time'

        skus = SKU.objects.order_by(sku_sort).filter(category_id=category_id)

        page = Paginator(object_list=skus, per_page=5)
        skus = page.page(page_id).object_list
        current_page = page_id
        total_page = page.num_pages
        content = {
            'categories': categories,
            'skus': skus,
            'category': category,
            'currentPage': current_page,
            'totalPage': total_page,
            'sort': sort
        }

        return render(request, 'list.html', context=content)


class SKUHotListView(View):
    def get(self, request, category_id):
        # 根据销量查询两条数据
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]

        hot_skus = []
        for sku in skus:
            hot_skus.append(
                {
                    'id': sku.id,
                    'name': sku.name,
                    'default_image_url': sku.default_image_url.url,
                    'price': sku.price
                }
            )
        content = {
            'hot_skus': hot_skus
        }

        return http.JsonResponse(content)


class SKUDetailView(View):
    def get(self, request, sku_id):

        categories = get_categories()
        try:
            sku = SKU.objects.get(id=sku_id)
            category = sku.category
        except:
            return http.HttpResponseForbidden('商品不存在')

        # # 构建当前商品的规格键
        # sku_specs = goods.specs.order_by('spec_id')
        # sku_key = []
        # for spec in sku_specs:
        #     sku_key.append(spec.option.id)
        # # 获取当前商品的所有SKU
        # skus = goods.spu.sku_set.all()
        # # 构建不同规格参数（选项）的sku字典
        # spec_sku_map = {}
        # for s in skus:
        #     # 获取sku的规格参数
        #     s_specs = s.specs.order_by('spec_id')
        #     # 用于形成规格参数-sku字典的键
        #     key = []
        #     for spec in s_specs:
        #         key.append(spec.option.id)
        #     # 向规格参数-sku字典添加记录
        #     spec_sku_map[tuple(key)] = s.id
        # # 获取当前商品的规格信息
        # goods_specs = goods.spu.specs.order_by('id')
        # # 若当前sku的规格信息不完整，则不再继续
        # if len(sku_key) < len(goods_specs):
        #     return
        # for index, spec in enumerate(goods_specs):
        #     # 复制当前sku的规格键
        #     key = sku_key[:]
        #     # 该规格的选项
        #     spec_options = spec.options.all()
        #     for option in spec_options:
        #         # 在规格参数sku字典中查找符合当前规格的sku
        #         key[index] = option.id
        #         option.sku_id = spec_sku_map.get(tuple(key))
        #     spec.spec_options = spec_options


        ##########################################################
        # 获取对应的spu
        spu = sku.spu

        skus = spu.sku_set.all()
        key_map = {}
        for _sku in skus:
            specs = _sku.specs.order_by('id').all()
            key = []
            for spec in specs:
                key.append(spec.option_id)
            key_map[tuple(key)] = _sku.id

        # spu对应的规格
        spu_specs = spu.specs.all()
        # 排除不符合规格的
        for key in key_map:
            if len(key) < len(spu_specs):
                return http.HttpResponse(status=400)
        # 获取现sku对应的规格id作为key
        sku_specs = sku.specs.order_by('id').all()
        key = []
        for sku_spec in sku_specs:
            key.append(sku_spec.option_id)

        for index, spu_spec in enumerate(spu_specs):
            spec_options = []
            for spec in spu_spec.options.all():
                _key = key[:]
                _key[index] = spec.id
                spec.sku_id = key_map.get(tuple(_key))
                spec_options.append(spec)
            spu_spec.spec_options = spec_options

        context = {
            'sku': sku,
            'categories': categories,
            'category': category,
            'specs': spu_specs
        }

        return render(request, 'detail.html', context=context)


class CategoryVisitCountView(View):

    def post(self, request, category_id):
        # 获取商品
        category = GoodsCategory.objects.get(id=category_id)
        local_time = time.localtime()
        time_str = '%d-%02d-%02d' % (local_time.tm_year, local_time.tm_mon, local_time.tm_mday)
        date = datetime.strptime(time_str, '%Y-%m-%d')
        try:
            visit = category.visit_counts.get(date=date)
        except:
            visit = GoodCategoryVisit()
            visit.category = category
            visit.date = date
        visit.count += 1
        visit.save()

        return http.JsonResponse({'msg': '浏览量增加成功'})


class BrowseHistoriesView(MyLoginRequest):
    def post(self, request):
        # 获取参数
        user = request.user
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')

        # 连接redis
        redis_conn = get_redis_connection('histories')
        redis_conn.lrem('history_%d' % user.id, 0, sku_id)
        redis_conn.lpush('history_%d' % user.id, sku_id)
        redis_conn.ltrim('history_%d' % user.id, 0, 4)

        return http.JsonResponse({'msg': '保存浏览记录成功'})

    def get(self, request):
        redis_conn = get_redis_connection('histories')
        sku_ids = redis_conn.lrange('history_%d' % request.user.id, 0, 4)
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'img': sku.default_image_url.url,
                'price': sku.price,
                'sales': sku.sales,
                'name': sku.name,
            })

        return http.JsonResponse({'skus': skus})
